//这里进行拦截 请求 和响应
import axios from 'axios';
import qs from 'qs'
let AUTH_TOKEN=(function(){
    return localStorage.getItem("token")
})()
var instance = axios.create({
})
instance.defaults.headers.common['Authorization']=AUTH_TOKEN
//拦截请求
instance.interceptors.request.use(function(config){
    config.method === 'post'
    ? config.data = qs.stringify({...config.data})
    : config.params = {...config.params};
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';

    let url = config.url;
    if(url.indexOf("login")>-1){
        localStorage.setItem('token',"");
        config.headers.Authorization = "";
    }
    if(url.indexOf("user")>-1 && url.indexOf("login")<0){
        config.headers.Authorization = localStorage.getItem("token")
    }
    return config
},function(err){
    return Promise.reject(err)
})

//拦截响应
instance.interceptors.response.use(function(res){
    if(res.headers.token){
        localStorage.setItem('token',res.headers.token)
    }
    return res
},function(err){
    console.log(err.response.status)
    //这里做请求拦截
    let text = JSON.parse(JSON.stringify(err)).response.status;
    console.log(text)
    if(text === 404){
        location.replace('http://localhost:8080/#/404')
    }else if(text === 500){
        location.replace('http://localhost:8080/#/500')
    }else{

    }
    return err
})
export default instance